<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="坐标点" prop="wisdomPoints">
        <el-input
          v-model="queryParams.wisdomPoints"
          placeholder="请输入坐标点"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="坐标名称" prop="wisdomName">
        <el-input
          v-model="queryParams.wisdomName"
          placeholder="请输入坐标名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区名称" prop="administrativeRegion">
        <el-select v-model="queryParams.administrativeRegion" multiple placeholder="选择区">
          <el-option v-for="(item,index) in regionList" :key="index" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺类型" label-width="120px" prop="merchantSale">
        <el-select v-model="queryParams.merchantSale" placeholder="选择店铺类型">
          <el-option label="普通店铺" value="0" />
          <el-option label="直营店" value="1" />
          <el-option label="加盟店" value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="详细地址" prop="introduceBriefly">
        <el-input
          v-model="queryParams.introduceBriefly"
          placeholder="请输入详细地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="区域概况" prop="regionalOverview">
        <el-input
          v-model="queryParams.regionalOverview"
          placeholder="请输入区域概况"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wisdom:wisdom:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wisdom:wisdom:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wisdom:wisdom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wisdom:wisdom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wisdomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="店铺logo" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.regionalOverview"
              fit="cover"
            ></el-image>
          </template>
      </el-table-column>
      <el-table-column label="坐标名称" align="center" prop="wisdomName" />
      <el-table-column label="坐标点" align="center" prop="wisdomPoints" />
      <el-table-column label="详细地址" align="center" prop="introduceBriefly" />
      <el-table-column label="所属区域" align="center" prop="administrativeRegion" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <!-- <el-table-column label="区域概况" align="center" prop="regionalOverview" /> -->
      <!-- <el-table-column label="区域简介" align="center" prop="regionalProfile" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wisdom:wisdom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wisdom:wisdom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改智慧地图对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-input placeholder="地址搜索" style="width:200px;margin-top:20px" v-model="searchContent" id="tipinput"></el-input>
        <!-- <input type="text" id="tipinput"> -->
        <div id="container2"></div>
        <el-form-item label="坐标点" prop="wisdomPoints">
          <el-input v-model="form.wisdomPoints" placeholder="请在地图上选点" />
        </el-form-item>
        <el-form-item label="店铺分类">
            <el-radio v-model="form.merchantSale" :label="0" size="large">普通店铺</el-radio>
            <el-radio v-model="form.merchantSale" :label="1" size="large">直营店</el-radio>
            <el-radio v-model="form.merchantSale" :label="2" size="large">加盟店</el-radio>
          </el-form-item>
        <el-form-item label="详细地址" prop="introduceBriefly">
          <el-input v-model="form.introduceBriefly" placeholder="请输入详细地址" />
        </el-form-item>
        <!-- <el-form-item label="地址logo" prop="regionalOverview">
          <el-input v-model="form.regionalOverview" placeholder="请输入区域概况" />
        </el-form-item> -->
        <el-form-item label="店铺logo" prop="regionalOverview"  :class="form.regionalOverview?'upHide':''">
          <el-upload
            ref="upload"
            :action="$uploadImage"
            list-type="picture-card"
            :on-success="uploadSuccess"
            :on-remove="removeImage"
            :on-error="uploadError"
            :before-upload="uploadBefore"
            :file-list="imageList"
            :headers="headers"
            name="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="坐标名称" prop="wisdomName">
          <el-input v-model="form.wisdomName" placeholder="请输入坐标名称" />
        </el-form-item>
        <!-- <el-form-item label="区域简介">
          <fileUpload v-model="form.regionalProfile"/>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWisdom, getWisdom, delWisdom, addWisdom, updateWisdom, exportWisdom } from "@/api/wisdom/wisdom";
import FileUpload from '@/components/FileUpload';
import { getToken } from '@/utils/auth'

export default {
  name: "Wisdom",
  components: {
    FileUpload,
  },
  data() {
    return {
      marker:null,
      imageList:[],
      regionList: [
        {
            label: '朝阳区',
            value: 0
        },
        {
            label: '南关区',
            value: 1
        },
        {
            label: '二道区',
            value: 2
        },
        {
            label: '宽城区',
            value: 3
        },
        {
            label: '绿园区',
            value: 4
        },
        // {
        //     label: '高新技术开发区',
        //     value: 5
        // },
        // {
        //     label: '经济技术开发区',
        //     value: 6
        // },
        {
            label: '净月区',
            value: 7
        },
        // {
        //     label: '汽车产业开发区',
        //     value: 8
        // },
        {
            label: '九台市',
            value: 9
        },
        {
            label: '农安县',
            value: 10
        },
        {
            label: '德惠市',
            value: 11
        },
        {
            label: '榆树市',
            value: 12
        },
        {
            label: '双阳区',
            value: 13
        }
      ],
      searchContent:'',
      // 遮罩层
      loading: true,
      map:null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 智慧地图表格数据
      wisdomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wisdomPoints: null,
        wisdomName: null,
        merchantSale:null,
        introduceBriefly: null,
        regionalOverview: null,
        administrativeRegion:[],
        regionalProfile: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        wisdomPoints:[
          {required:true,message:'请在地图上选点',trigger: 'change'}
        ],
        wisdomName:[
          {required:true,message:'请输入坐标名称',trigger: 'change'}
        ],
        introduceBriefly:[
          {required:true,message:'请输入详细地址',trigger: 'change'}
        ],
        // regionalOverview:[
        //   {required:true,message:'请选择地址logo',trigger: 'change'}
        // ]
      }
    };
  },
  created() {
    this.getList();
  },
  computed:{
    headers(){
      return {
        'Authorization':'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    }
  },
  methods: {
    // 删除图片
    removeImage(){
      this.form.regionalOverview = ""
    },
    uploadError(){
      this.form.regionalOverview = ""
    },
    uploadBefore(){
      this.form.regionalOverview = "1"
    },
    // 上传成功
    uploadSuccess(e){
      this.loading =false
      console.log(e,'上传成功')
      this.$set(this.form,'regionalOverview',e.data[0])
      this.$refs.form.validateField(['regionalOverview'])
    },
    mapInit(centerPointer){
      let that = this
      console.log('地图初始化')
      this.map&&this.map.destory&&this.map.destory()
      this.map = new AMap.Map("container2", {
        center: centerPointer||[125.317468,43.890349],
        zoom: 10
      });
      //输入提示
      var autoOptions = {
          input: "tipinput"
      };
      AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete','AMap.Geocoder'], function(){
          var auto = new AMap.AutoComplete(autoOptions);
          var placeSearch = new AMap.PlaceSearch({
              map: that.map
          });  //构造地点查询类
          auto.on("select", select);//注册监听，当选中某条记录时会触发
          function select(e) {
              placeSearch.setCity(e.poi.adcode);
              placeSearch.search(e.poi.name);  //关键字查询查询
              placeSearch.on('markerClick',function(e){
                console.log(e)
                // let icon = '//webapi.amap.com/theme/v1.3/images/newpc/way_btn2.png'
                // let content = '<div class="map_point">当前选择</div>'
                //   that.marker = new AMap.Marker({
                //       icon, // 自定义点标记
                //       content,
                //       position: centerPointer, // 基点位置
                //       offset: new AMap.Pixel(0,0), // 设置点标记偏移量
                //       anchor:'bottom-center', // 设置锚点方位
                //   });
                //   that.map.add(that.marker);
                if(that.marker){
                  that.map.remove(that.marker)
                }
                  that.form.wisdomPoints = JSON.stringify([e.event.lnglat.lng,e.event.lnglat.lat])
                  that.geocoder.getAddress([e.event.lnglat.lng,e.event.lnglat.lat], function(status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        // result为对应的地理位置详细信息
                        console.log(result)
                        that.form.introduceBriefly = result.regeocode.formattedAddress
                    }
                  })
              })
          }
          that.geocoder = new AMap.Geocoder()
      });
      let icon = '//webapi.amap.com/theme/v1.3/images/newpc/way_btn2.png'
      let content = '<div class="map_point">当前选择</div>'
      if(centerPointer){
        that.map.clearMap();
        that.marker = new AMap.Marker({
            icon, // 自定义点标记
            content,
            position: centerPointer, // 基点位置
            offset: new AMap.Pixel(0,0), // 设置点标记偏移量
            anchor:'bottom-center', // 设置锚点方位
        });
        that.map.add(that.marker);
        that.form.wisdomPoints = JSON.stringify(centerPointer)
      }
      this.map.on('click',(e)=>{
        // that.map.clearMap();
        if(that.marker){
          that.map.remove(that.marker)
        }
        that.marker = new AMap.Marker({
            icon, // 自定义点标记
            content,
            position: [e.lnglat.lng,e.lnglat.lat], // 基点位置
            offset: new AMap.Pixel(0,0), // 设置点标记偏移量
            anchor:'bottom-center', // 设置锚点方位
        });
        that.map.add(that.marker);
        that.form.wisdomPoints = JSON.stringify([e.lnglat.lng,e.lnglat.lat])
        that.geocoder.getAddress([e.lnglat.lng,e.lnglat.lat], function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              console.log(result)
              that.form.introduceBriefly = result.regeocode.formattedAddress
          }
        })
      })
      
    },
    /** 查询智慧地图列表 */
    getList() {
      this.loading = true;
      let queryParams = JSON.parse(JSON.stringify(this.queryParams))
      if(queryParams.merchantSale === null){
        delete queryParams.merchantSale
      }
      queryParams.administrativeRegion = queryParams.administrativeRegion.join(',')
      if(queryParams.administrativeRegion == ''){
        delete queryParams.administrativeRegion
      }
      console.log(queryParams)
      listWisdom(queryParams).then(response => {
        this.wisdomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        merchantSale:0,
        wisdomPoints: null,
        wisdomName: null,
        introduceBriefly: null,
        regionalOverview: null,
        regionalProfile: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.searchContent=''
      this.reset();
      this.open = true;
      this.title = "添加智慧地图";
      this.imageList = []
      this.$nextTick(()=>{
        this.mapInit()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.searchContent=''
      this.reset();
      const id = row.id || this.ids
      getWisdom(id).then(response => {
        this.form = response.data;
        this.form.merchantSale = this.form.merchantSale||0
        this.open = true;
        this.title = "修改智慧地图";
        this.imageList = [{
          name:'图片',
          url:response.data.regionalOverview
        }]
        this.$nextTick(()=>{
          this.mapInit(JSON.parse(this.form.wisdomPoints))
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWisdom(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWisdom(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除智慧地图编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWisdom(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      let queryParams = JSON.parse(JSON.stringify(this.queryParams))
      if(queryParams.merchantSale === null){
        delete queryParams.merchantSale
      }
      queryParams.administrativeRegion = queryParams.administrativeRegion.join(',')
      if(queryParams.administrativeRegion == ''){
        delete queryParams.administrativeRegion
      }
      let that = this
      this.$confirm('是否确认导出所有智慧地图数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          that.loading = true
          return exportWisdom(queryParams);
        }).then(response => {
          that.loading = false
          this.download(response.msg);
        }).catch(e=>{
          that.loading = false
        })
    }
  }
};
</script>
<style>
.upHide .el-upload{
  display: none;
}
.amap-sug-result{
  z-index: 9999;
}
.map_point{
    background: #fff;
    width: 100px;
    text-align: center;
    border: 1px solid #ececec;
    border-radius: 5px;
    box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.12);
    transition: all 0.3s ease-in-out;
}
</style>
<style scoped>
#container2{
  width: 100%;
  height: 50vh;
  margin: 10px 0;
}

</style>